package com.minjiang.blog.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;


/**
 * 切面编程
 * @Aspect 切面类
 * @Component 扫描类
 */
@Aspect
@Component
@Slf4j
public class LogAspect {
    /**
     * 获取本类的日志
     */
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 设置切面方法和切面点，
     */
    @Pointcut(value = "execution(public * com.minjiang.blog.controller..*(..))*")
    public void log() {
    }

    /**
     * 执行前
     * @param joinPoint
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        //获取属性
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //获取属性请求
        HttpServletRequest request = attributes.getRequest();
        //获取url
        String url = request.getRequestURI().toString();
        //获取ip
        String ip = request.getRemoteAddr();
        //获取classMethode
        String classMethod = joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
        //获取参数
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url,ip,classMethod, args);
        logger.info("Request : {}",requestLog);
    }

    /**
     * 执行后
     */
    @After("log()")
    public void doAfter(){
        logger.info("-------doAfter-----------");
    }

    /**
     * 将日志执行完的返回结果赋值给result
     * @param result
     */
    @AfterReturning(returning = "result", pointcut = "log()")
    public void doAfterReturn(Object result){
        logger.info("Result : {}",result);
    }

    /**
     * 分装数据
     */
    private class RequestLog{
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "RequestLog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }

}
